package com.ssw.backend.service.impl.user.acount;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ssw.backend.mapper.UserMapper;
import com.ssw.backend.pojo.User;
import com.ssw.backend.service.user.RegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RegisterServiceImpl implements RegisterService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Override
    public Map<String, String> register(String username, String password, String confirmedPassword) {
        Map<String,String> map =new HashMap<>();
        if(username==null){
            map.put("error_message","用户名不能为空");
            return map;
        }
        if(password==null || confirmedPassword==null){
            map.put("error_message","密码不能为空");
            return map;
        }

        username = username.trim();
        if(username.length()==0)
        {
            map.put("error_message","用户名不能为空");
            return map;
        }
        if(password.length()==0||confirmedPassword.length()==0){
            map.put("error_message","密码不能为空");
            return map;
        }
        if(username.length()>100){
            map.put("error_message","用户名不能超过100");
            return map;
        }
        if(password.length()>100||confirmedPassword.length()>100){
            map.put("error_message","密码不能超过100");
            return map;
        }
        if(!password.equals(confirmedPassword))
        {
            map.put("error_message","两次密码输入不一致");
            return map;
        }

        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",username);
        List<User> users=userMapper.selectList(queryWrapper);
        if(!users.isEmpty()){
            map.put("error_message","用户名已存在");
            return map;
        }
        String encodePassword=passwordEncoder.encode(password);
        String photo="https://cdn.acwing.com/media/user/profile/photo/141541_lg_f625d1069d.jpg";
        User user=new User(null,username,encodePassword,1500,photo,null);
        userMapper.insert(user);

        map.put("error_message","success");
        return map;
    }
}
